package com.cy.store.controller;

import com.cy.store.entity.Address;
import com.cy.store.service.IAddressService;
import com.cy.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("addresses")
public class AddressController extends BaseController{

    @Autowired
    IAddressService addressService;

    /**
     * 添加地址
     */
    @RequestMapping("add_new_address")
    JsonResult<Void> addNewAddress(HttpSession session, Address address){

        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);

        Integer rows = addressService.addNewAddress(uid, username, address);

        return new JsonResult<>(OK);
    }


    /**
     * 地址显示
     */
    @RequestMapping({"", "/"})
    JsonResult<List<Address>> getByUid(HttpSession session){
        List<Address> data = addressService.getByUid(getuidFromSession(session));
        return new JsonResult<>(OK, data);
    }

    /**
     * 更新默认地址
     */
    @RequestMapping("{aid}/set_default")
    JsonResult<Void> setDefault(@PathVariable("aid") Integer aid, HttpSession session){
        

        addressService.setDefault(aid, getuidFromSession(session), getUsernameFromSession(session));

        return new JsonResult<>(OK);
    }


    /**
     * 删除地址
     */
    @RequestMapping("{aid}/delete")
    JsonResult<Void> delete(@PathVariable("aid") Integer aid, HttpSession session){

        addressService.delete(aid, getuidFromSession(session), getUsernameFromSession(session));
        return new JsonResult<>(OK);
    }


    @RequestMapping("{aid}/update")
    JsonResult<Void> update(Address address){
        addressService.update(address);
        return new JsonResult<>(OK);
    }

}
